import { DataTypes, Model, Sequelize } from 'sequelize';

export interface CallLogAttributes {
  id?: number;
  session_id: string;
  tool_name: string;
  input_params: Record<string, any>;
  output_result?: Record<string, any> | null;
  execution_time_ms: number;
  status: 'success' | 'error' | 'timeout';
  error_message?: string | null;
  user_agent?: string | null;
  ip_address?: string | null;
  created_at?: Date;
}

export interface CallLogCreationAttributes extends Omit<CallLogAttributes, 'id' | 'created_at'> {}

export class CallLog extends Model<CallLogAttributes, CallLogCreationAttributes> implements CallLogAttributes {
  declare id: number;
  declare session_id: string;
  declare tool_name: string;
  declare input_params: Record<string, any>;
  declare output_result?: Record<string, any> | null;
  declare execution_time_ms: number;
  declare status: 'success' | 'error' | 'timeout';
  declare error_message?: string | null;
  declare user_agent?: string | null;
  declare ip_address?: string | null;
  
  // timestamps!
  declare readonly created_at: Date;

  static initModel(sequelize: Sequelize): typeof CallLog {
    return CallLog.init(
      {
        id: {
          type: DataTypes.INTEGER,
          primaryKey: true,
          autoIncrement: true,
        },
        session_id: {
          type: DataTypes.STRING(255),
          allowNull: false,
          comment: '会话ID，用于关联同一会话的多次调用',
        },
        tool_name: {
          type: DataTypes.STRING(100),
          allowNull: false,
          comment: '调用的工具名称',
        },
        input_params: {
          type: DataTypes.JSON,
          allowNull: false,
          comment: '输入参数',
        },
        output_result: {
          type: DataTypes.JSON,
          allowNull: true,
          comment: '输出结果',
        },
        execution_time_ms: {
          type: DataTypes.INTEGER,
          allowNull: false,
          comment: '执行时间（毫秒）',
        },
        status: {
          type: DataTypes.ENUM('success', 'error', 'timeout'),
          allowNull: false,
          defaultValue: 'success',
          comment: '执行状态',
        },
        error_message: {
          type: DataTypes.TEXT,
          allowNull: true,
          comment: '错误信息',
        },
        user_agent: {
          type: DataTypes.STRING(500),
          allowNull: true,
          comment: '用户代理',
        },
        ip_address: {
          type: DataTypes.STRING(45),
          allowNull: true,
          comment: 'IP地址',
        },
      },
      {
        sequelize,
        tableName: 'call_logs',
        timestamps: true,
        createdAt: 'created_at',
        updatedAt: false,
        indexes: [
          {
            fields: ['session_id'],
            name: 'idx_call_logs_session_id',
          },
          {
            fields: ['tool_name'],
            name: 'idx_call_logs_tool_name',
          },
          {
            fields: ['status'],
            name: 'idx_call_logs_status',
          },
          {
            fields: ['created_at'],
            name: 'idx_call_logs_created_at',
          },
          {
            fields: ['tool_name', 'status', 'created_at'],
            name: 'idx_call_logs_analytics',
          },
        ],
      }
    );
  }
}

export interface UsageStatAttributes {
  id?: number;
  date: string; // YYYY-MM-DD 格式
  tool_name: string;
  total_calls: number;
  success_calls: number;
  error_calls: number;
  timeout_calls: number;
  avg_execution_time_ms: number;
  max_execution_time_ms: number;
  min_execution_time_ms: number;
  unique_sessions: number;
  updated_at?: Date;
}

export interface UsageStatCreationAttributes extends Omit<UsageStatAttributes, 'id' | 'updated_at'> {}

export class UsageStat extends Model<UsageStatAttributes, UsageStatCreationAttributes> implements UsageStatAttributes {
  declare id: number;
  declare date: string;
  declare tool_name: string;
  declare total_calls: number;
  declare success_calls: number;
  declare error_calls: number;
  declare timeout_calls: number;
  declare avg_execution_time_ms: number;
  declare max_execution_time_ms: number;
  declare min_execution_time_ms: number;
  declare unique_sessions: number;
  
  // timestamps!
  declare readonly updated_at: Date;

  static initModel(sequelize: Sequelize): typeof UsageStat {
    return UsageStat.init(
      {
        id: {
          type: DataTypes.INTEGER,
          primaryKey: true,
          autoIncrement: true,
        },
        date: {
          type: DataTypes.DATEONLY,
          allowNull: false,
          comment: '统计日期 YYYY-MM-DD',
        },
        tool_name: {
          type: DataTypes.STRING(100),
          allowNull: false,
          comment: '工具名称',
        },
        total_calls: {
          type: DataTypes.INTEGER,
          allowNull: false,
          defaultValue: 0,
          comment: '总调用次数',
        },
        success_calls: {
          type: DataTypes.INTEGER,
          allowNull: false,
          defaultValue: 0,
          comment: '成功调用次数',
        },
        error_calls: {
          type: DataTypes.INTEGER,
          allowNull: false,
          defaultValue: 0,
          comment: '错误调用次数',
        },
        timeout_calls: {
          type: DataTypes.INTEGER,
          allowNull: false,
          defaultValue: 0,
          comment: '超时调用次数',
        },
        avg_execution_time_ms: {
          type: DataTypes.FLOAT,
          allowNull: false,
          defaultValue: 0,
          comment: '平均执行时间（毫秒）',
        },
        max_execution_time_ms: {
          type: DataTypes.INTEGER,
          allowNull: false,
          defaultValue: 0,
          comment: '最大执行时间（毫秒）',
        },
        min_execution_time_ms: {
          type: DataTypes.INTEGER,
          allowNull: false,
          defaultValue: 0,
          comment: '最小执行时间（毫秒）',
        },
        unique_sessions: {
          type: DataTypes.INTEGER,
          allowNull: false,
          defaultValue: 0,
          comment: '唯一会话数',
        },
      },
      {
        sequelize,
        tableName: 'usage_stats',
        timestamps: true,
        createdAt: false,
        updatedAt: 'updated_at',
        indexes: [
          {
            fields: ['date', 'tool_name'],
            unique: true,
            name: 'uk_usage_stats_date_tool',
          },
          {
            fields: ['date'],
            name: 'idx_usage_stats_date',
          },
          {
            fields: ['tool_name'],
            name: 'idx_usage_stats_tool_name',
          },
        ],
      }
    );
  }
}